package com.bookshop.controller;

import com.bookshop.bean.PageBean;
import com.bookshop.bean.ResultBean;
import com.bookshop.bean.TypeBean;
import com.bookshop.dao.TypeDao;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TypeController {

    @Resource
    private TypeDao typeDao;

    @RequestMapping("/add_type")
    public ResultBean addType(String typeName,String typeDepict){
        ResultBean result = new ResultBean();
        TypeBean type = new TypeBean();
        type.setTypeName(typeName);
        type.setTypeDepict(typeDepict);

        if(typeDao.insertType(type) == 1){
            result.setCode(1);
            result.setMsg("添加类型成功");
        }else {
            result.setCode(-1);
            result.setMsg("添加类型失败");
        }
        return result;
    }

    /**
     * 查出所有类型
     * @return
     */
    @RequestMapping("/find_types")
    public ResultBean findTypes(){
        List<TypeBean> types = typeDao.selectAllTypes();
        ResultBean result = new ResultBean();
        result.setCode(1);
        result.setData(types);
        return result;
    }

    @RequestMapping("/find_types_page")
    public ResultBean findTypesPage(Integer pageNow){
        PageBean page = new PageBean();
        page.setRowCount(typeDao.getRowCount());
        page.setPageCount(page.getRowCount()%page.getPageSize()==0
                            ?page.getRowCount()/page.getPageSize()
                            :page.getRowCount()/page.getPageSize()+1);
        page.setPageNow(pageNow==null?1:
                        pageNow<1?1:
                        pageNow>page.getPageCount()?page.getPageCount():pageNow);

        List<TypeBean> types = typeDao.selectAllTypesPages(page);
        ResultBean result = new ResultBean();
        result.setCode(1);

        Map<String,Object> map = new HashMap<>();
        map.put("types",types);
        map.put("page",page);

        result.setData(map);
        return result;
    }

    @RequestMapping("/drop_type")
    public ResultBean dropType(Integer id){
        ResultBean result = new ResultBean();
        if(typeDao.deleteType(id) == 1){
            result.setCode(1);
            result.setMsg("删除类型成功");
        }else{
            result.setCode(-1);
            result.setMsg("删除类型失败");
        }
        return result;
    }

    @RequestMapping("/edit_type")
    public ResultBean editType(TypeBean type){
        ResultBean result = new ResultBean();
        if(typeDao.updateType(type)==1){
            result.setCode(1);
            result.setMsg("修改类型成功");
        }else {
            result.setCode(-1);
            result.setMsg("修改类型失败");
        }
        return result;
    }




















}
